<template>
  <el-dialog :visible.sync="dialogLogin" width="400px" :close-on-click-modal="false">
    <div class="bg-blue-500">
      <div class="login bg-white">
        <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="账号">
              <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="loginForm.password" type="password" auto-complete="off" placeholder="密码"
              @keyup.enter.native="handleLogin">
              <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
            </el-input>
          </el-form-item>
          <el-form-item prop="code">
            <div class="flex">
              <el-input v-model="loginForm.code" auto-complete="off" placeholder="验证码" style="width: 63%"
                @keyup.enter.native="handleLogin">
                <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
              </el-input>
              <div class="login-code">
                <img :src="codeUrl" @click="getCode" class="login-code-img" />
              </div>
            </div>
          </el-form-item>
          <el-form-item>
            <div class="flex content-center justify-between">
              <el-checkbox v-model="loginForm.rememberMe">记住密码</el-checkbox>
              <div class="text-right text-blue-500 cursor-pointer">
                <router-link :to="{ name: 'forgetPassword' }">忘记密码</router-link>
              </div>
            </div>
          </el-form-item>

          <el-form-item style="width: 100%">
            <el-button :loading="loading" size="medium" type="primary" style="width: 100%"
              @click.native.prevent="handleLogin">
              <span v-if="!loading">登 录</span>
              <span v-else>登 录 中...</span>
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" style="width: 100%" @click="toRegister">免费注册</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import Cookies from 'js-cookie'
import { getToken } from '@/utils/auth'
import { getCodeImg } from '@/api/login'

import { encrypt, decrypt } from '@/utils/jsencrypt'
import { mapActions, mapGetters } from 'vuex'

export default {
  name: 'LoginPoup',
  props: {
    // dialogLogin: {
    //   type: Boolean,
    //   default: false,
    // },
  },
  data () {
    return {
      dialogLogin: false,
      codeUrl: '',
      loading: false,
      loginForm: {
        username: '',
        password: '',
        rememberMe: false,
        uuid: '',
        code: '',
      },
      loginRules: {
        username: [
          { required: true, trigger: 'blur', message: '用户名不能为空' },
        ],
        password: [
          { required: true, trigger: 'blur', message: '密码不能为空' },
        ],
      },
    }
  },
  computed: {
    ...mapGetters({
      token: 'token',
      userName: 'name',
    }),
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect
        if (route.query.isShowLogin) {
          this.dialogLogin = true
        }
      },
      immediate: true,
    },
    dialogLogin (v) {
      let ishasshowLogin = this.$route.query.isShowLogin
      if (ishasshowLogin && !v) {
        this.$router.push({
          path: '/',
        })
      }
    },
  },
  created () {
    if (this.token) {
      this.GetInfo()
    } else {
      this.getCode()
    }
  },
  methods: {
    ...mapActions({
      LogOut: 'LogOut', // 第一个blogAdd是定义的一个函数别名称，挂载在到this(vue)实例上，后面一个blogAdd 才是actions里面函数方法名称
      GetInfo: 'GetInfo',
    }),
    signIn () {
      this.$router.push({
        path: '/login',
      })
      this.getCookie()
      if (this.token) {
        this.GetInfo()
      } else {
        this.getCode()
      }
    },
    signOut () {
      this.LogOut().then(() => {
        let fullPath = this.$route.path
        if(fullPath ==='/index' || fullPath === '/'){
          return 
        }
        this.$router.push({
          path: '/',
        })
      })
    },
    getCode () {
      getCodeImg().then((res) => {
        this.codeUrl = 'data:image/gif;base64,' + res.img
        this.loginForm.uuid = res.uuid
      })
    },

    getCookie () {
      const username = Cookies.get('username')
      const password = Cookies.get('password')
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password:
          password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
      }
    },

    capctchaCheckSuccess (params) {
      this.loginForm.code = params.captchaVerification
      this.loading = true
      if (this.loginForm.rememberMe) {
        Cookies.set('username', this.loginForm.username, { expires: 30 })
        Cookies.set('password', encrypt(this.loginForm.password), {
          expires: 30,
        })
        Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 })
      } else {
        Cookies.remove('username')
        Cookies.remove('password')
        Cookies.remove('rememberMe')
      }
      this.$store
        .dispatch('Login', this.loginForm)
        .then(() => {
          this.$router.push({ path: this.redirect || '/' }).catch(() => { })
        })
        .catch(() => {
          this.loading = false
        })
    },

    handleLogin () {
      if (getToken()) {
        this.$router.push({ path: '/user' })
        return
      }

      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true
          if (this.loginForm.rememberMe) {
            Cookies.set('username', this.loginForm.username, { expires: 30 })
            Cookies.set('password', encrypt(this.loginForm.password), {
              expires: 30,
            })
            Cookies.set('rememberMe', this.loginForm.rememberMe, {
              expires: 30,
            })
          } else {
            Cookies.remove('username')
            Cookies.remove('password')
            Cookies.remove('rememberMe')
          }
          this.$store
            .dispatch('Login', this.loginForm)
            .then(() => {
              // this.$router.push({ path: this.redirect || "/" }).catch(() => {});
              this.$router.push({ path: '/user' }).catch(() => { })
            })
            .catch(() => {
              this.loading = false
              this.getCode()
            })
        }
      })
    },

    toRegister () {
      this.$router.push({ path: '/register' })
    },
  },
}
</script>

<style>
</style>
